import { queryCutInLog } from '../services/api';
import moment from 'moment';

function method(str, a, b) {
    let type = 'string';
    if (str === 'updateTime') {
        type = 'date';
    } else if (str === 'progId') {
        type = 'num';
    }
    switch (type) {
        case 'num': // 数字排序
            return a - b;
        case 'date': // 日期排序，IE8下'2012-12-12'这种格式无法设置时间，替换成'/'
            return moment(a).unix() - moment(b).unix();
        default:
            // 字符串排序
            return a.localeCompare(b);
    }
}
export default {
    namespace: 'cutinlog',

    state: {
        list: [],
        pagination: {},
    },

    effects: {
        *fetch({ payload }, { call, put }) {
            const response = yield call(queryCutInLog, payload);
            let dataSource = response.interCutLogs;
            if (payload) {
                if (payload.sorter) {
                    const s = payload.sorter.split('_');
                    if (s[1] === 'descend') {
                        dataSource = dataSource.sort((prev, next) => method(s[0], next[s[0]], prev[s[0]]));
                    } else {
                        dataSource = dataSource.sort((prev, next) => method(s[0], prev[s[0]], next[s[0]]));
                    }
                }

                let pageSize = 10;
                if (payload.pageSize) {
                    pageSize = payload.pageSize * 1;
                }

                const result = {
                    list: Array.isArray(response.interCutLogs) ? dataSource : [],
                    pagination: {
                        total: response.pageInfo.pageTotal,
                        pageSize,
                        current: parseInt(payload.page, 10) || 1,
                    },
                };

                //console.log('log', result);
                yield put({
                    type: 'save',
                    payload: result,
                });
            }
        },
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                list: action.payload.list,
                pagination: action.payload.pagination,
            };
        },
    },
};
